package app.dws;


import Bean.UserLoginBean;
import app.dwd.BaseAppV1;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import common.Constant;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;

import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import util.AtguiguUtil;
import util.FlinkSinkUtil;

import java.time.Duration;

public class Dws_DwsUserUserLoginWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_DwsUserUserLoginWindow().init(
                4004,
                2,
                "Dws_DwsUserUserLoginWindow",
                Constant.TOPIC_DWD_TRAFFIC_PAGE
        );
    }
    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        // 1. 过滤登录页面记录
        SingleOutputStreamOperator<JSONObject> loginPageStream = findLoginPage(stream);
        // 2. 转成 pojo 类型
        SingleOutputStreamOperator<UserLoginBean> beanStream = parseToObject(loginPageStream);
        // 3. 开窗聚合
        SingleOutputStreamOperator<UserLoginBean> resultStream = windowAndAgg(beanStream);
        // 4. 写出到 clickhouse 中
        writeToClikeHouse(resultStream);
    }
    // 4. 写出到 clickhouse 中
    private void writeToClikeHouse(SingleOutputStreamOperator<UserLoginBean> resultStream) {
        resultStream
                .addSink(FlinkSinkUtil.getClickHouseSink("dws_user_user_login_window",
                        UserLoginBean.class));
    }

    // 3. 开窗聚合
    private SingleOutputStreamOperator<UserLoginBean> windowAndAgg(SingleOutputStreamOperator<UserLoginBean> beanStream) {
        return beanStream
                .assignTimestampsAndWatermarks(WatermarkStrategy
                        .<UserLoginBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                .withTimestampAssigner((bean,ts)->bean.getTs()))
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .aggregate(new AggregateFunction<UserLoginBean, Tuple2<Long, Long>, UserLoginBean>() {
                               @Override
                               public Tuple2<Long, Long> createAccumulator() {
                                   return Tuple2.of(0L, 0L);
                               }

                               @Override
                               public Tuple2<Long, Long> add(UserLoginBean value, Tuple2<Long, Long> acc) {
                                   return Tuple2.of(value.getUuCt() + acc.f0, value.getBackCt() + acc.f1);
                               }

                               @Override
                               public UserLoginBean getResult(Tuple2<Long, Long> acc) {
                                   return new UserLoginBean("", "", acc.f1, acc.f0,
                                           System.currentTimeMillis());
                               }

                               @Override
                               public Tuple2<Long, Long> merge(Tuple2<Long, Long> a, Tuple2<Long, Long> b) {
                                   return null;
                               }
                           },
                        new ProcessAllWindowFunction<UserLoginBean, UserLoginBean, TimeWindow>() {
                            @Override
                            public void process(Context ctx, Iterable<UserLoginBean> elements, Collector<UserLoginBean> out) throws Exception {
                                UserLoginBean bean = elements.iterator().next();
                                bean.setStt(AtguiguUtil.toDatTime(ctx.window().getStart()));
                                bean.setEdt(AtguiguUtil.toDatTime(ctx.window().getEnd()));
                                out.collect(bean);
                            }
                        });

    }

    // 2. 转成 pojo 类型
    private SingleOutputStreamOperator<UserLoginBean> parseToObject(
            SingleOutputStreamOperator<JSONObject> loginPageStream) {
        return loginPageStream
                .keyBy(obj -> obj.getJSONObject("common").getString("uid"))
                .process(new KeyedProcessFunction<String, JSONObject, UserLoginBean>() {

                    private ValueState<String> lastVisitDateState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        lastVisitDateState = getRuntimeContext()
                                .getState(new ValueStateDescriptor<String>("lastVisitDateState",
                                        String.class
                                ));
                    }

                    @Override
                    public void processElement(JSONObject obj,
                                               Context ctx,
                                               Collector<UserLoginBean> out) throws Exception {
                        Long ts = obj.getLong("ts");


                        long backCt = 0L;
                        long uuCt = 0L;
                        // TODO
                        String today = AtguiguUtil.toDate(ts);
                        String lastVisitDate = lastVisitDateState.value();
                        if (!today.equals(lastVisitDate)) {
                            // 今天的第一次登录
                            uuCt = 1L;
                            lastVisitDateState.update(today);

                            // 需要判断是否为7 日回流用户
                            if (lastVisitDate != null) {
                                // 证明以前登录过, 需要判断是否为 回流
                                if ((ts - AtguiguUtil.dateToTs(lastVisitDate)) / 1000 / 60 / 60 / 24 >= 7) {
                                    backCt = 1L;
                                }
                            }
                        }
                        UserLoginBean bean = new UserLoginBean("", "",
                                backCt, uuCt,
                                ts
                        );

                        if (uuCt == 1) {
                            out.collect(bean);
                        }
                    }
                });
    }

    // 1. 过滤登录页面记录
    private SingleOutputStreamOperator<JSONObject> findLoginPage(DataStreamSource<String> stream) {
        return stream
                .map(JSON::parseObject)
                .filter(new FilterFunction<JSONObject>() {
                    @Override
                    public boolean filter(JSONObject value) throws Exception {
                        String uid = value.getJSONObject("common").getString("uid");
                        String lastPageId = value.getJSONObject("page").getString("last_page_id");
                        return uid!=null && (lastPageId==null || "login".equals(lastPageId));
                    }
                });
    }
}
